<template>
    <Dropdown trigger="click" @on-click="setTheme">
        <a href="javascript:void(0)">
            <Icon :style="{marginTop: '-2px', verticalAlign: 'middle'}" color="#495060" :size="18" type="paintbucket"></Icon>
            <Icon type="arrow-down-b"></Icon>
        </a>
        <DropdownMenu slot="list">
            <DropdownItem v-for="(item, index) in themeList" :key="index" :name="item.name">
                <Row type="flex" justify="center" align="middle">
                     <span><Icon :size="22" type="record" :color="item.element"/></span>
                </Row>
            </DropdownItem>
        </DropdownMenu>
    </Dropdown>
</template>

<script>
    import Cookies from 'js-cookie';
    export default {
        name: 'themeDropdownMenu',
        data() {
            return {
                themeList: [{
                    name: 'black_b',
                    element: '#2d8cf0'
                }, {
                    name: 'black_g',
                    element: '#64d572'
                }, {
                    name: 'black_y',
                    element: '#ffd572'
                }]
            };
        },
        methods: {
            setTheme(themeFile) {
                let mainTheme = themeFile.substr(-1, 1);
                console.log('mainTheme is:' + mainTheme);
                let path = '';
                let themeLink = document.querySelector('link[name="theme"]');
                let userName = Cookies.get('user');
                if (localStorage.theme) {
                    let themeList = JSON.parse(localStorage.theme);
                    let index = 0;
                    let hasThisUser = themeList.some((item, i) => {
                        if (item.userName === userName) {
                            index = i;
                            return true;
                        } else {
                            return false;
                        }
                    });
                    if (hasThisUser) {
                        themeList[index].mainTheme = mainTheme;
                    } else {
                        themeList.push({
                            userName: userName,
                            mainTheme: mainTheme
                        });
                    }
                    localStorage.theme = JSON.stringify(themeList);
                } else {
                    localStorage.theme = JSON.stringify([{
                        userName: userName,
                        mainTheme: mainTheme
                    }]);
                }
                if (mainTheme !== 'b') {
                    path = 'dist/' + mainTheme + '.css';
                } else {
                    path = '';
                }
                themeLink.setAttribute('href', path);
            }
        }
    };
</script>